package com.hrs.core.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.hrs.enity.vo.DepartmentVo;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 摆渡人
 * @description
 * @date 2023/1/12 22:41
 */
@Service
public class DepartmentTreeService {
    public List<DepartmentVo> buildDeptTree(List<DepartmentVo> departmentVoList) {
        if (CollectionUtils.isEmpty(departmentVoList)) {
            return new ArrayList<DepartmentVo>();
        }
        List<DepartmentVo> list =
                departmentVoList.stream().filter(e -> e.getParentId() == null || e.getParentId() == 0).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<DepartmentVo>();
        }
        this.buildDeptTree(list, departmentVoList);
        return list;
    }

    public void buildDeptTree(List<DepartmentVo> nodeList,List<DepartmentVo> departmentVoList) {
        int nodeSize = nodeList.size();
        for (int i = 0; i < nodeSize; i++) {
            int preIndex = i - 1;
            int nextIndex = i + 1;
            DepartmentVo node = nodeList.get(i);
            if (preIndex > -1) {
                node.setPreId(nodeList.get(preIndex).getId());
            }
            if (nextIndex < nodeSize) {
                node.setNextId(nodeList.get(nextIndex).getId());
            }
            buildDeptTree(node, departmentVoList);
        }
    }

    public void buildDeptTree(DepartmentVo node,List<DepartmentVo> departmentVoList) {
        List<DepartmentVo> children = getChildren(node, departmentVoList);
        if (CollectionUtils.isNotEmpty(children)) {
            node.setChildrenDepartment(children);
            this.buildDeptTree(children, departmentVoList);
        }
    }

    private List<DepartmentVo> getChildren(DepartmentVo node, List<DepartmentVo> departmentVOList) {
        Long id = node.getId();
        return departmentVOList.stream().filter(e -> id.equals(e.getParentId())).collect(Collectors.toList());
    }
}
